package cn.edu.tju.wallet.service;

import cn.edu.tju.wallet.domain.Transaction;
import cn.edu.tju.wallet.domain.Transaction.TransactionType;
import cn.edu.tju.wallet.dto.TransactionDTO;
import cn.edu.tju.wallet.repository.TransactionRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class TransactionQueryService {

    @Autowired
    private TransactionRepository transactionRepository;

    /**
     * 查询交易流水（分页）（完全遵循指南代码）
     */
    public Page<TransactionDTO> getTransactions(Long walletId, int page, int size) {
        Pageable pageable = PageRequest.of(page, size);
        Page<Transaction> transactions = transactionRepository
                .findByWalletIdOrderByCreateTimeDesc(walletId, pageable);

        return transactions.map(this::toDTO);
    }

    /**
     * 按类型查询（完全遵循指南代码）
     */
    public Page<TransactionDTO> getTransactionsByType(
            Long walletId,
            TransactionType type,
            int page,
            int size) {
        Pageable pageable = PageRequest.of(page, size);
        Page<Transaction> transactions = transactionRepository
                .findByWalletIdAndTypeOrderByCreateTimeDesc(walletId, type, pageable);

        return transactions.map(this::toDTO);
    }

    /**
     * 按时间范围查询（修正指南笔误：findByWalletIdAndCreateTimeBetween）
     */
    public Page<TransactionDTO> getTransactionsByTimeRange(
            Long walletId,
            LocalDateTime startTime,
            LocalDateTime endTime,
            int page,
            int size) {
        Pageable pageable = PageRequest.of(page, size);
        Page<Transaction> transactions = transactionRepository
                .findByWalletIdAndCreateTimeBetweenOrderByCreateTimeDesc(walletId, startTime, endTime, pageable);

        return transactions.map(this::toDTO);
    }

    /**
     * 转换为DTO（完全遵循指南代码）
     */
    private TransactionDTO toDTO(Transaction transaction) {
        // 转换为DTO
        return new TransactionDTO(transaction);
    }
}